#include "pch.h"
#include "tx_video_render_wnd.h"
#include "framework.h"
#include "afxdialogex.h"

#define MAX_VIDEO_BUFFER_WIDTH 1920
#define MAX_VIDEO_BUFFER_HEIGHT 1080

BEGIN_MESSAGE_MAP(TxVideoRenderWnd, CWnd)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_WM_ERASEBKGND()
	ON_WM_SIZE()
END_MESSAGE_MAP()

TxVideoRenderWnd::TxVideoRenderWnd()
{
	_yuvData.resize(MAX_VIDEO_BUFFER_WIDTH * MAX_VIDEO_BUFFER_HEIGHT * 1.5);
	memset(_yuvData.data(), 32, MAX_VIDEO_BUFFER_WIDTH * MAX_VIDEO_BUFFER_HEIGHT);
	memset(_yuvData.data()+ MAX_VIDEO_BUFFER_WIDTH * MAX_VIDEO_BUFFER_HEIGHT, 128, (MAX_VIDEO_BUFFER_WIDTH * MAX_VIDEO_BUFFER_HEIGHT) / 2);
}

TxVideoRenderWnd::~TxVideoRenderWnd()
{

}

int TxVideoRenderWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	_glEnv = ITxRenderer::create();
	_glEnv->OnCreate((void*)this);

	return 0;
}

void TxVideoRenderWnd::OnDestroy()
{
	if (_glEnv)
	{
		_glEnv->OnDestory();
		_glEnv.reset();
	}

	CWnd::OnDestroy();
}

BOOL TxVideoRenderWnd::OnEraseBkgnd(CDC* pDC)
{
	if (_glEnv)
	{
		_glEnv->Render(_yuvData.data(), _width, _height);
	}
	return TRUE;
}

void TxVideoRenderWnd::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);

	if (_glEnv)
	{
		_glEnv->OnSize(cx, cy);
	}
}

void TxVideoRenderWnd::Render(uint8_t* data, int len, int width, int height)
{

	if (width * height<0 || width * height*1.5>_yuvData.size())
	{
		return;
	}

	memcpy(_yuvData.data(), data, len);
	_width = width;
	_height = height;
	Invalidate();
}